/**
 * 缓冲式输出更新器 - 解决AI连续输出字符导致的界面闪烁问题
 */
export class BufferedOutputUpdater {
  private buffer: string = '';
  private isThinking: boolean = false;
  private thinkingContent: string = '';
  private toolCalls: any[] = [];
  private toolResults: any[] = [];
  private lastUpdate: number = 0;
  private updateTimer: NodeJS.Timeout | null = null;
  private flushTimer: NodeJS.Timeout | null = null;
  
  private readonly bufferSize: number;
  private readonly flushTimeout: number;
  private readonly minUpdateInterval: number;
  
  constructor(
    private callback: (content: string, isThinking?: boolean, thinkingContent?: string, toolCalls?: any[], toolResults?: any[]) => void,
    options: {
      bufferSize?: number;
      flushTimeout?: number;
      minUpdateInterval?: number;
    } = {}
  ) {
    this.bufferSize = options.bufferSize || 100;
    this.flushTimeout = options.flushTimeout || 50;
    this.minUpdateInterval = options.minUpdateInterval || 16; // 60fps
  }

  /**
   * 添加内容到缓冲区
   */
  addContent(
    content: string, 
    isThinking?: boolean, 
    thinkingContent?: string, 
    toolCalls?: any[], 
    toolResults?: any[]
  ): void {
    this.buffer = content;
    this.isThinking = isThinking || false;
    this.thinkingContent = thinkingContent || '';
    this.toolCalls = toolCalls || [];
    this.toolResults = toolResults || [];

    // 如果是工具状态变化或thinking状态变化，立即更新
    if (this.isStatusChange(isThinking, toolCalls)) {
      this.flush();
      return;
    }

    // 如果缓冲区达到大小限制，触发更新
    if (this.buffer.length >= this.bufferSize) {
      this.scheduleUpdate();
      return;
    }

    // 设置或重置强制刷新定时器
    this.resetFlushTimer();
  }

  /**
   * 检查是否为状态变化（需要立即更新）
   */
  private isStatusChange(isThinking?: boolean, toolCalls?: any[]): boolean {
    return (
      // thinking状态变化
      this.isThinking !== (isThinking || false) ||
      // 工具调用状态变化
      (toolCalls && toolCalls.length > 0) ||
      // 工具结果变化
      (this.toolResults && this.toolResults.length > 0)
    );
  }

  /**
   * 调度更新（考虑最小更新间隔）
   */
  private scheduleUpdate(): void {
    const now = Date.now();
    const timeSinceLastUpdate = now - this.lastUpdate;

    if (timeSinceLastUpdate >= this.minUpdateInterval) {
      // 可以立即更新
      this.flush();
    } else {
      // 需要等待到最小间隔
      if (this.updateTimer) {
        clearTimeout(this.updateTimer);
      }
      
      const delay = this.minUpdateInterval - timeSinceLastUpdate;
      this.updateTimer = setTimeout(() => {
        this.flush();
      }, delay);
    }
  }

  /**
   * 重置强制刷新定时器
   */
  private resetFlushTimer(): void {
    if (this.flushTimer) {
      clearTimeout(this.flushTimer);
    }
    
    this.flushTimer = setTimeout(() => {
      this.flush();
    }, this.flushTimeout);
  }

  /**
   * 立即刷新缓冲区
   */
  flush(): void {
    // 清除所有定时器
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
      this.updateTimer = null;
    }
    
    if (this.flushTimer) {
      clearTimeout(this.flushTimer);
      this.flushTimer = null;
    }

    // 执行回调
    try {
      this.callback(
        this.buffer,
        this.isThinking,
        this.thinkingContent,
        this.toolCalls,
        this.toolResults
      );
    } catch (error) {
      console.error('缓冲输出回调执行失败:', error);
    }

    // 更新最后更新时间
    this.lastUpdate = Date.now();
  }

  /**
   * 强制最终刷新（流结束时调用）
   */
  finalFlush(): void {
    this.flush();
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    if (this.updateTimer) {
      clearTimeout(this.updateTimer);
      this.updateTimer = null;
    }
    
    if (this.flushTimer) {
      clearTimeout(this.flushTimer);
      this.flushTimer = null;
    }
    
    this.buffer = '';
    this.isThinking = false;
    this.thinkingContent = '';
    this.toolCalls = [];
    this.toolResults = [];
  }
}

/**
 * Thinking内容更新器 - 专门处理thinking内容的定时更新
 */
export class ThinkingUpdater {
  private content: string = '';
  private updateTimer: NodeJS.Timeout | null = null;
  private readonly updateInterval: number;
  
  constructor(
    private callback: (thinkingContent: string) => void,
    updateInterval: number = 200 // 默认200ms更新间隔
  ) {
    this.updateInterval = updateInterval;
  }

  /**
   * 更新thinking内容
   */
  updateContent(content: string): void {
    this.content = content;
    
    // 如果没有运行定时器，启动定时更新
    if (!this.updateTimer) {
      this.startTimer();
    }
  }

  /**
   * 启动定时器
   */
  private startTimer(): void {
    this.updateTimer = setInterval(() => {
      if (this.content) {
        try {
          this.callback(this.content);
        } catch (error) {
          console.error('Thinking更新回调执行失败:', error);
        }
      }
    }, this.updateInterval);
  }

  /**
   * 停止更新
   */
  stop(): void {
    if (this.updateTimer) {
      clearInterval(this.updateTimer);
      this.updateTimer = null;
    }
  }

  /**
   * 最终更新并停止
   */
  finalUpdate(): void {
    if (this.content) {
      try {
        this.callback(this.content);
      } catch (error) {
        console.error('Thinking最终更新回调执行失败:', error);
      }
    }
    this.stop();
  }

  /**
   * 清理资源
   */
  cleanup(): void {
    this.stop();
    this.content = '';
  }
}